package com.lizhi.note.service.impl;


import com.lizhi.note.dto.NotebookDTO;
import com.lizhi.note.entity.NotebookEntity;
import com.lizhi.note.mapper.NotebookMapper;
import com.lizhi.note.repository.NotebookRepository;
import com.lizhi.note.service.NotebookService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class NotebookServiceImpl implements NotebookService {

    private final NotebookRepository notebookRepository;
    private final NotebookMapper notebookMapper;

    public NotebookServiceImpl(NotebookRepository notebookRepository, NotebookMapper notebookMapper) {
        this.notebookRepository = notebookRepository;
        this.notebookMapper = notebookMapper;
    }

    @Override
    public NotebookDTO createNotebook(NotebookDTO notebookDto) {
        NotebookEntity entity = notebookMapper.toEntity(notebookDto);
        NotebookEntity savedEntity = notebookRepository.save(entity);
        return notebookMapper.toDto(savedEntity);
    }

    @Override
    public Optional<NotebookDTO> getNotebookById(Long id) {
        return notebookRepository.findById(id)
                .map(notebookMapper::toDto);
    }

    @Override
    public List<NotebookDTO> getAllNotebooks() {
        List<NotebookEntity> entities = notebookRepository.findAll();
        return notebookMapper.toDtoList(entities);
    }

    @Override
    public NotebookDTO updateNotebook(NotebookDTO notebookDto) {
        NotebookEntity entity = notebookRepository.findById(notebookDto.getId())
                .orElseThrow(() -> new IllegalArgumentException("笔记本不存在"));
        // todo
        // 使用MapStruct更新实体
        notebookMapper.updateEntity(notebookDto, entity);

        NotebookEntity updatedEntity = notebookRepository.save(entity);
        return notebookMapper.toDto(updatedEntity);
    }

    @Override
    public void deleteNotebook(Long id) {
        notebookRepository.deleteById(id);
    }
}
